package org.danng.taobao;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.danng.domain.TaoBaoItem;
import org.danng.domain.TaobaoItemSku;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taobao.api.domain.Item;
import com.taobao.api.domain.Sku;

@Service
public class ItemManager {
	private ItemDAO itemDAO;

	@Autowired
	public void setItemDAO(ItemDAO itemDAO) {
		this.itemDAO = itemDAO;
	}

	public void saveItemWithSkus(Item item) throws Throwable {
		TaoBaoItem dest = new TaoBaoItem();
		try {
			PropertyUtils.copyProperties(dest, item);
			List<TaobaoItemSku> taobaoItemSkus = new ArrayList<TaobaoItemSku>();
			List<Sku> skus = item.getSkus();
			if(CollectionUtils.isNotEmpty(skus)){
			for (Sku orig : skus) {
				TaobaoItemSku itemSku = new TaobaoItemSku();
				PropertyUtils.copyProperties(itemSku, orig);
				taobaoItemSkus.add(itemSku);
			}
			dest.setSkus(taobaoItemSkus);
			}
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		itemDAO.addItem(dest);
	}

}
